/**
 * 时间格式化方法
 *
 * @param {(object | string | number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time: any, cFormat: any) {
  if (arguments.length === 0)
    return null

  let date
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'

  if (typeof time === 'object') {
    date = time
  }
  else {
    if (typeof time === 'string' && /^\d+$/.test(time))
      time = Number.parseInt(time)

    if (typeof time === 'number' && time.toString().length === 10)
      time = time * 1000

    date = new Date(time.replace(/-/g, '/'))
  }

  const formatObj: any = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  }

  const time_str = format.replace(/\{([ymdhisa])+\}/g, (result: any, key: any) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a')
      return ['日', '一', '二', '三', '四', '五', '六'][value]

    return value.toString().padStart(2, '0')
  })

  return time_str
}

/**
 * 人性化显示时间
 *
 * @param {object} datetime
 */
export function beautifyTime(datetime = '') {
  if (datetime == null)
    return ''

  datetime = datetime.replace(/-/g, '/')

  const time = new Date()
  let outTime = new Date(datetime)
  if (/^[1-9]\d*$/.test(datetime))
    outTime = new Date(Number.parseInt(datetime) * 1000)

  if (time.getFullYear() !== outTime.getFullYear())
    return parseTime(outTime, '{y}/{m}/{d}')

  if (time.getMonth() !== outTime.getMonth())
    return parseTime(outTime, '{m}/{d}')

  if (time.getDate() !== outTime.getDate()) {
    const day = outTime.getDate() - time.getDate()
    if (day === -1)
      return parseTime(outTime, '昨天 {h}:{i}')

    if (day === -2)
      return parseTime(outTime, '前天 {h}:{i}')

    return parseTime(outTime, '{m}-{d}')
  }

  if (time.getHours() !== outTime.getHours())
    return parseTime(outTime, '{h}:{i}')

  let minutes = outTime.getMinutes() - time.getMinutes()
  if (minutes === 0)
    return '刚刚'

  minutes = Math.abs(minutes)
  return `${minutes}分钟前`
}

/**
 * 货币格式化
 * @param price
 */
function formatPrice(price: number) {
  return String(Number(price).toFixed(2)).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
// 返回格式化金额
export function unitPrice(val: number, unit?: string, location?: string) {
  if (!val)
    val = 0
  const price = formatPrice(val)
  if (location === 'before')
    return price.substr(0, price.length - 3)

  if (location === 'after')
    return price.substr(-2)

  return (unit || '') + price
}
